//
//  AddNewBankCartVC.m
//  NtoccDriver
//
//  Created by mac on 2019/11/22.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "AddNewBankCartVC.h"
#import "HDPicModle.h"
#import "GetPhoto.h"
#import "ZHFAddTitleAddressView.h"
#import "SelectBankCartVC.h"
#import "SelectOpenCartAddrVC.h"

@interface AddNewBankCartVC ()<ZHFAddTitleAddressViewDelegate>
@property(nonatomic,strong)ZHFAddTitleAddressView * addTitleAddressView;
@property (nonatomic,strong) CJTextField *fieldBankName;
@property (nonatomic,copy) NSString *strBankCode;
@property (nonatomic,strong) CJTextField *tfBankCartType; //银行类型
@property (nonatomic,copy) NSString *strBankCartTypeCode; //银行类型
@property (nonatomic,strong) CJTextField *fieldBankCardNum;
@property (nonatomic,strong) CJTextField *fieldPersonName;
@property (nonatomic,strong) CJLabel *labPersonTitle;
@property (nonatomic,strong) CJTextField *fieldPersonPhone;
@property (nonatomic,strong) CJTextField *fieldOpenCartAddr; // 开户网点
@property (nonatomic,strong) CJTextField *fieldOpenCartCity; // 开户城市
@property (nonatomic,strong) CJTextField *fieldAccountType;
@property (nonatomic,copy) NSString *strAccountTypeCode;
@property (nonatomic,copy) NSString *strCityName;
@property (nonatomic,copy) NSString *strProvinceName;
@property (nonatomic,copy) NSString *strCityCode;
@property (nonatomic,copy) NSString *strProvinceCode;
@property (nonatomic,copy) NSString *strSelectType; // 0 开户行 1 账户类型
@property (nonatomic,copy) NSString *strBankAssociationNumber;  // 银行联行号
@property (nonatomic,copy) NSString *isDefault; // 是否默认
@end

@implementation AddNewBankCartVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    if (self.isEdit) {
        [self setTitleName:@"编辑银行卡"];
    }else{
        [self setTitleName:@"新增银行卡"];
    }
    [self setBackLeftButton:@""];
    [self createTopView];
//    [self getBankListCart];
    [self setUI];
    self.strCityName = @"";
    self.strProvinceName = @"";
    self.strCityCode = @"";
    self.strProvinceCode = @"";
    
    [self setTextFieldLimit];
    
    if (self.isEdit) {
        [self setEditInfo];
    }
}
- (void)setEditInfo{
    
    self.fieldPersonName.text = self.model.name;
    self.fieldPersonPhone.text = self.model.mobile;
    self.fieldBankCardNum.text = self.model.account;
    self.fieldBankName.text = self.model.bankName;
    self.strProvinceName = self.model.province;
    self.strCityName = self.model.city;
    self.fieldOpenCartAddr.text = self.model.branche;
    self.strAccountTypeCode = @(self.model.type).cj_description;
    self.fieldAccountType.text = self.model.type == 1 ? @"个人账户":@"企业账户";
    self.strBankCode = self.model.bankNo;
    //  isDefault
    self.isDefault = @(self.model.isDefault).cj_description;
    self.strCityCode = self.model.provinceCode;
    self.strProvinceCode = self.model.cityCode;
    self.strBankAssociationNumber = self.model.bankAssociationNumber;
    // 开户城市  accountCity
    self.fieldOpenCartCity.text = self.model.accountCity;
    // 银行类型
    self.tfBankCartType.text = self.model.cardTypeName;
    self.strBankCartTypeCode = self.model.cardType;
}
/// 创建tableview 等
- (void)createTopView{

    CGRect rcFrame = CGRectMake(0, kTopHeight +1, [[UIScreen mainScreen] bounds].size.width, 0);
    FlexFrameView *header = [[FlexFrameView alloc] initWithFlex:[CJControl getShowMyBank] ? @"AddNewBankCartInputView":@"AddNewBankCartView" Frame:rcFrame Owner:self];
    header.flexibleHeight = YES;
    
    if ([CJControl getIsCompanyAndStaff]) {
        self.labPersonTitle.text = @"开户企业名称";
        self.fieldPersonName.placeholder = @"请填写开户企业名称";
    }else{
        self.labPersonTitle.text = @"开户人姓名";
        self.fieldPersonName.placeholder = @"请填写开户人姓名";
    }

    [header layoutIfNeeded];
    [self.view addSubview:header];
}

- (void)getBankListCart{
    
    WS(ws);
    [CJNetWork getSenGoodsDicsTypeinfo:CJGetSendgoodsBank Success:^(id  _Nullable responseObject) {

        //        NSArray *list= responseObject[@"dictList"];
        NSDictionary *dic = responseObject[0];
        NSArray *list = dic[@"dictList"];
        NSString *strTitle = dic[@"name"];
        NSMutableArray *arrCodes = [[NSMutableArray alloc]init];
        NSMutableArray *arrName = [[NSMutableArray alloc]init];

        if (list.count > 0 && !IsNilOrNull(list)) {
            
            [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSDictionary *dic = (NSDictionary *)obj;
                [arrCodes addObject:dic[@"code"]];
                [arrName addObject:dic[@"name"]];
            }];
            [ws btnSelectTypeActionWithType:@"2" withCodeArr:arrCodes withNameArr:arrName withTitleName:strTitle];
        }else{
            [CJAlert showStringDismissWithDelay:@"暂无数据"];
        }
        

    }];
}

- (void)btnSelectTypeActionWithType:(NSString *)strType withCodeArr:(NSMutableArray *)arrCode withNameArr:(NSMutableArray *)arrBame withTitleName:(NSString *)strTitle{
    
    [self.view endEditing:NO];
    BRStringPickerView *stringPickerView = [[BRStringPickerView alloc]initWithPickerMode:BRStringPickerComponentSingle];
    stringPickerView.title = strTitle;
    stringPickerView.dataSourceArr = arrBame;
    WS(ws);
    stringPickerView.resultModelBlock = ^(BRResultModel *resultModel) {
        if (strType.intValue == 0) {
            ws.fieldBankName.text = resultModel.selectValue;
            ws.strBankCode = arrCode[resultModel.index];
        } else if(strType.intValue == 1){
            ws.fieldAccountType.text = resultModel.selectValue;
            ws.strAccountTypeCode = arrCode[resultModel.index];
        } else if(strType.intValue == 2){
            ws.tfBankCartType.text = resultModel.selectValue;
            ws.strBankCartTypeCode = arrCode[resultModel.index];
        }
    };
    
    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:[UIColor cjMainColor]];
    stringPickerView.pickerStyle = customStyle;
    [stringPickerView show];
}

- (void)btnOpenBankCartNameAction{
//    [self.view endEditing:NO];
//    self.strSelectType = @"0";
//    [self getBankListCart];
    
    DLog(@"选择开户行");
    WS(ws);
    SelectBankCartVC *vc = [[SelectBankCartVC alloc]init];
    vc.blockBankInfo = ^(id anyObject) {
        NSDictionary *dic = anyObject;
        ws.fieldBankName.text = dic[@"name"];
        ws.strBankCode = dic[@"code"];
        ws.strBankAssociationNumber = @"";
        ws.fieldOpenCartAddr.text = @"";
    };
    [self pushVc:vc];
}


/// 选择银行卡 类型
- (void)btnOpenBankCartTypeAction{
    
    WS(ws);
    [CJNetWork getSenGoodsDicsTypeinfo:CJCardType Success:^(id  _Nullable responseObject) {
          
        DLog(@"=====  %@",responseObject);
        NSDictionary *dic = responseObject[0];
        NSArray *list = dic[@"dictList"];
        NSString *strTitle = dic[@"name"];
        NSMutableArray *arrCodes = [[NSMutableArray alloc]init];
        NSMutableArray *arrName = [[NSMutableArray alloc]init];

        if (list.count > 0 && !IsNilOrNull(list)){
            [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSDictionary *dic = (NSDictionary *)obj;
                [arrCodes addObject:dic[@"code"]];
                [arrName addObject:dic[@"name"]];
            }];
            [ws btnSelectTypeActionWithType:@"2" withCodeArr:arrCodes withNameArr:arrName withTitleName:strTitle];
        }else{
            [CJAlert showStringDismissWithDelay:@"暂无数据"];
        }
        
    }];
    
}


/// 开户网点
- (void)btnSelectOpenCartAddrAction{
    WS(ws);
    if ([CJRegular getIsStrEmpty:self.strBankCode]) {
        [CJAlert showStringDismissWithDelay:@"请先选择开户银行"];
    }else{
        SelectOpenCartAddrVC *vc = [[SelectOpenCartAddrVC alloc]init];
        vc.bankCode = self.strBankCode;
        vc.blockAddrInfo = ^(id anyObject) {
            NSDictionary *dic = anyObject;
            ws.strBankAssociationNumber = dic[@"bankNo"];
            ws.fieldOpenCartAddr.text = dic[@"bankName"];
        };
        [self pushVc:vc];
    }
}


- (void)btnOpenBankAddrCityNameAction{
    [self.view endEditing:NO];
    [self.addTitleAddressView addAnimate];
}

-(void)cancelBtnClick:(NSString *)titleAddress titleID:(NSString *)titleID{
//    [self.addressBtn setTitle:titleAddress forState:UIControlStateNormal];
    NSLog( @"%@   %@",titleAddress,  [NSString stringWithFormat:@"%@",titleID]);
    NSArray *arr = [titleAddress componentsSeparatedByString:@","];
    NSArray *arrCode = [titleID componentsSeparatedByString:@","];

    if (arr.count >= 2) {
        self.strProvinceName = arr[0];
        self.strCityName = arr[1];
        self.strCityCode = arrCode[0];
        self.strProvinceCode = arrCode[1];
        self.fieldOpenCartCity.text = CJStringWithFormat(@"%@%@",arr[0],arr[1]);
    }
}
-(void)setUI{
    
    //山东省 临沂市 兰山区   打印的对应省市县的id=37 =3713 = 371302
    self.addTitleAddressView = [[ZHFAddTitleAddressView alloc]init];
    self.addTitleAddressView.title = @"选择地址";
    self.addTitleAddressView.delegate1 = self;
    self.addTitleAddressView.defaultHeight = 350;
    self.addTitleAddressView.titleScrollViewH = 37;
    self.addTitleAddressView.isSelectCity = YES;
    if (self.addTitleAddressView.titleIDMarr.count > 0) {
        self.addTitleAddressView.isChangeAddress = true;
    }
    else{
        self.addTitleAddressView.isChangeAddress = false;
    }
//    self.addTitleAddressView.isChangeAddress  = YES;
    [self.view addSubview:[self.addTitleAddressView initAddressView]];
}


- (void)btnAccountTypeAction{
    [self.view endEditing:NO];
//    self.strSelectType = @"1";
    NSMutableArray *arrcode = [[NSMutableArray alloc]initWithObjects:@"1",@"2", nil];
    NSMutableArray *arrName = [[NSMutableArray alloc]initWithObjects:@"个人账户",@"企业账户", nil];

    [self btnSelectTypeActionWithType:@"1" withCodeArr:arrcode withNameArr:arrName withTitleName:@"账户类型"];
}
 - (void)setTextFieldLimit{
    
    self.fieldPersonName.textFieldType = CJTextFieldStringTypeNone;
    self.fieldPersonName.maxLength = CJTextLengthMax;
    
    self.fieldPersonPhone.textFieldType = CJTextFieldStringTypeNumber;
    self.fieldPersonPhone.maxLength = CJTextLengthPhone;
    
    self.fieldBankCardNum.textFieldType = CJTextFieldStringTypeNumber;
    self.fieldBankCardNum.maxLength = CJTextLengthMax;
//    开户网点
    self.fieldOpenCartAddr.textFieldType = CJTextFieldStringTypeNone;
    self.fieldOpenCartAddr.maxLength = CJTextLengthMax;

}

- (void)btnSaveInfoAction{
    //,text:6222081812002934027
//    [CJAlert showStringDismissWithDelay:@"隐私协议"];
    NSString *originalString = _fieldBankCardNum.text;
    NSArray *components = [originalString componentsSeparatedByString:@" "];
    NSString *noSpacesString = [components componentsJoinedByString:@""];
    if ([CJRegular getIsStrEmpty:self.strBankCode]) {
        [CJAlert showStringDismissWithDelay:@"请选择开户银行"];
    }else if ([CJRegular getIsStrEmpty:self.strBankCartTypeCode]){
        [CJAlert showStringDismissWithDelay:self.tfBankCartType.placeholder];
    }else if ([CJRegular getIsStrEmpty:self.fieldBankCardNum.text]){
        [CJAlert showStringDismissWithDelay:@"请填写正确格式的银行卡号"];
    }else if ([CJRegular getIsStrEmpty:self.fieldPersonName.text]){
        [CJAlert showStringDismissWithDelay:@"请填写开户人姓名"];

    }else if (![CJRegular getcheckPhone:self.fieldPersonPhone.text]){
         [CJAlert showStringDismissWithDelay:@"请填写正确格式的手机号"];
    }else if ([CJRegular getIsStrEmpty:self.strAccountTypeCode]){
        [CJAlert showStringDismissWithDelay:@"请选择账户类型"];
    }else if ([CJRegular getIsStrEmpty:self.fieldOpenCartAddr.text]){
        [CJAlert showStringDismissWithDelay:@"请选择开户网点"];
    }else if ([CJRegular getIsStrEmpty:self.strProvinceName]){
        [CJAlert showStringDismissWithDelay:@"请选择开户城市"];
    }else{
        
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/bankCard",CJBaseUrl);
        
        if (self.isEdit) {
            NSDictionary *dicPar = @{
                @"name":[CJControl getThreeUnaryValueStr:self.fieldPersonName.text],
                @"mobile":[CJControl getThreeUnaryValueStr:self.fieldPersonPhone.text],
                @"account":[CJControl getThreeUnaryValueStr:noSpacesString],
                @"bankName":[CJControl getThreeUnaryValueStr:self.fieldBankName.text],
                @"province":[CJControl getThreeUnaryValueStr:self.strProvinceName],
                @"city":[CJControl getThreeUnaryValueStr:self.strCityName],
                @"branche":[CJControl getThreeUnaryValueStr:self.fieldOpenCartAddr.text],
                @"type":[CJControl getThreeUnaryValueStr:self.strAccountTypeCode],
                @"bankNo":[CJControl getThreeUnaryValueStr:self.strBankCode],
                @"branchCode":[CJControl getBranchCode],
                @"isDefault":@(self.model.isDefault),
                @"provinceCode":[CJControl getThreeUnaryValueStr:self.strCityCode],
                @"cityCode":[CJControl getThreeUnaryValueStr:self.strProvinceCode],
                @"bankAssociationNumber":[CJControl getThreeUnaryValueStr:self.strBankAssociationNumber],
                @"code":self.model.code,
                @"cardType":[CJControl getThreeUnaryValueStr:self.strBankCartTypeCode],
                @"cardTypeName":[CJControl getThreeUnaryValueStr:self.tfBankCartType.text],
                @"bindCardStatus":CJStringWithFormat(@"%ld",(long)self.model.bindCardStatus)
            };
            
            WS(ws);
            [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PutType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
                [ws pop];
            } failure:^(NSError * _Nonnull error) {
                
            }];
            
        }else{
            
            NSDictionary *dicPar =@{
                @"name":[CJControl getThreeUnaryValueStr:self.fieldPersonName.text],
                @"mobile":[CJControl getThreeUnaryValueStr:self.fieldPersonPhone.text],
                @"account":[CJControl getThreeUnaryValueStr:noSpacesString],
                @"bankName":[CJControl getThreeUnaryValueStr:self.fieldBankName.text],
                @"province":[CJControl getThreeUnaryValueStr:self.strProvinceName],
                @"city":[CJControl getThreeUnaryValueStr:self.strCityName],
                @"branche":[CJControl getThreeUnaryValueStr:self.fieldOpenCartAddr.text],
                @"type":[CJControl getThreeUnaryValueStr:self.strAccountTypeCode],
                @"bankNo":[CJControl getThreeUnaryValueStr:self.strBankCode],
                @"branchCode":[CJControl getBranchCode],
                @"isDefault":@"0",
                @"provinceCode":[CJControl getThreeUnaryValueStr:self.strCityCode],
                @"cityCode":[CJControl getThreeUnaryValueStr:self.strProvinceCode],
                @"bankAssociationNumber":[CJControl getThreeUnaryValueStr:self.strBankAssociationNumber],
                @"cardType":[CJControl getThreeUnaryValueStr:self.strBankCartTypeCode],
                @"cardTypeName":[CJControl getThreeUnaryValueStr:self.tfBankCartType.text],
                @"bindCardStatus":@"0"

            };
            
            WS(ws);
            [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PostType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
                [ws pop];
            } failure:^(NSError * _Nonnull error) {
                
            }];
            
        }
        
    }

}

/// 上传图片
- (void)btnTouchUploadBankCartImgAction{
    
    WS(ws);
      [GetPhoto getPhoto:self completion:^(UIImage *curImage, NSData *imageData) {

          [ws upLoadImageUImage:curImage withNSData:imageData];
          
      }];
}

- (void)upLoadImageUImage:(UIImage *)img withNSData:(NSData *)imageData{

    WS(ws);
    [CJNetWork upLoadImageUImage:img withNSData:imageData Success:^(id  _Nullable responseObject) {
//        ws.imgVHeader.image = img;
//        [ws changePersonInfowithString:(NSString *)responseObject];
        [ws getAouthInfoWithImgUrl:(NSString *)responseObject];
    }];
    
}

- (void)getAouthInfoWithImgUrl:(NSString *)strImgV{
    
    NSDictionary *dicPra = @{
        @"image":strImgV,
        @"ocrType":@"ocrBankCard"
    };
    
   NSString *strURL = CJStringWithFormat(@"%@/ntocc-tps-api/ocr/card",CJBaseUrl);
    WS(ws);
    [[HDNetworking sharedHDNetworking] GETWithNoMsgOnshow:strURL parameters:dicPra success:^(id  _Nonnull responseObject) {
        
        DLog(@"======%@",responseObject);
//        {
//          "msg": "银行卡识成功",
//          "data": {
//            "data": {
//              "bankCardNumber": "8888888888888888",
//              "validDate": "NO VALID",
//              "bankCardType": 1,
//              "bankName": "贵阳银行"
//            },
//            "msg": "操作成功",
//            "status": 0
//          },
//          "status": 0
//        }
        
        NSDictionary *dicData = (NSDictionary *)responseObject;
        
        if ([[CJControl getThreeUnaryValueStr:dicData[@"bankCardNumber"]] isEqualToString:@"无"] || [[CJControl getThreeUnaryValueStr:dicData[@"bankCardNumber"]] isEqualToString:@""]) {
//            ws.fieldBankCardNum.text = @"";
//            ws.fieldBankCardNum.placeholder = @"请选择开户银行";

        }else{
            ws.fieldBankCardNum.text = [CJControl getThreeUnaryValueStr:dicData[@"bankCardNumber"]];
        }

//        if ([[CJControl getThreeUnaryValueStr:dicData[@"bankCode"]] isEqualToString:@"无"] || [[CJControl getThreeUnaryValueStr:dicData[@"bankCode"]] isEqualToString:@""] || IsNilOrNull(dicData[@"bankCode"])) {
//
//            [ws getBankListwithBankName:[CJControl getThreeUnaryValueStr:dicData[@"bankName"]]];
//
//        }else{
//            ws.strBankCode = [CJControl getThreeUnaryValueStr:dicData[@"bankCode"]];
//
//
//            if ([[CJControl getThreeUnaryValueStr:dicData[@"bankName"]] isEqualToString:@"无"] || [[CJControl getThreeUnaryValueStr:dicData[@"bankName"]] isEqualToString:@""]) {
//    //            ws.labBankName.text = @"";
//            }else{
//                ws.fieldBankName.text = [CJControl getThreeUnaryValueStr:dicData[@"bankName"]];
//            }
//        }
        
    } failure:^(NSError * _Nonnull error) {
       DLog(@"++++++++%@",error);

    }];
}

- (void)getBankListwithBankName:(NSString *)strBankName{
    
    WS(ws);
    [CJNetWork getSenGoodsDicsTypeinfo:CJGetSendgoodsBank Success:^(id  _Nullable responseObject) {
        DLog(@"======%@",responseObject);
        NSDictionary *dict = responseObject[0];
        NSArray *list = dict[@"dictList"];
//        NSArray *list= responseObject[@"dictList"];
    
        [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            
            NSDictionary *dic = list[idx];
            NSString *name = dic[@"name"];
            
            if ([name isEqualToString:strBankName]) {
                ws.fieldBankName.text = name;
                ws.strBankCode = dic[@"code"];
                return ;
            }
        }];
        
    }];
}


@end


